import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

export default class BaseEntity<T> {
    public data!: T
    protected client!: AxiosInstance
    protected options: AxiosRequestConfig = {
        baseURL: 'http://localhost:5200/',
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        }
    }

    /**
     * Initialize new base transfer entity
     * @param data Which data will be posted by request
     */
    constructor(data: T) {
        this.data = data
    }

    /**
     * Build request instance
     */
    getInstance() {
        this.client = axios.create(this.options)
        this.client.interceptors.request.use(this.beforeRequest, this.onRequestFailed)
        this.client.interceptors.response.use(this.onServerResponse, this.onServerError)
        return this
    }

    async post(url: string, config?: AxiosRequestConfig) {
        return await this.client.post(url, this.data, config)
    }

    async put(url: string, config?: AxiosRequestConfig) {
        return await this.client.put(url, this.data, config)
    }

    async get(url: string) {
        return await this.client.get(url)
    }

    async delete(url: string) {
        return await this.client.delete(url)
    }

    beforeRequest(config: AxiosRequestConfig): AxiosRequestConfig | Promise<AxiosRequestConfig> {
        console.log(config)
        return config
    }

    onRequestFailed(err: any) {
        console.log(err.response)
        return err.response
    }

    onServerResponse(response: AxiosResponse): AxiosResponse | Promise<AxiosResponse> {
        console.log(response.status)
        return response
    }

    onServerError(err: any) {
        console.log(err.response)
        return err.response
    }
}
